package com.huiminpay.merchant.controller;

import com.huiminpay.common.cache.domain.BusinessException;
import com.huiminpay.common.cache.domain.CommonErrorCode;
import com.huiminpay.common.cache.domain.PageVO;
import com.huiminpay.common.cache.util.QRCodeUtil;
import com.huiminpay.merchant.api.MerchantService;
import com.huiminpay.merchant.common.util.SecurityUtil;
import com.huiminpay.merchant.dto.MerchantDTO;
import com.huiminpay.merchant.dto.StoreDTO;
import com.huiminpay.transaction.api.TransactionService;
import com.huiminpay.transaction.api.dto.QRCodeDto;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: 有点儿意思
 * @Description:
 */
@Slf4j
@RestController
public class StoreController {

    @Reference
    MerchantService merchantService;

    @Reference
    TransactionService transactionService;

    @Value("${huiminpay.c2b.subject}")
    String subject;
    @Value("${huiminpay.c2b.body}")
    String body;

    @PostMapping("/my/stores/merchants/page")
    public PageVO<StoreDTO> queryStoreByPage(@RequestParam Integer pageNo,@RequestParam Integer pageSize){
        Long merchantId = SecurityUtil.getMerchantId();
        StoreDTO storeDTO = new StoreDTO();
        storeDTO.setMerchantId(merchantId);
        return merchantService.queryStoreByPage(storeDTO, pageNo, pageSize);
    }

    @ApiOperation("生成门店二维码")
    @GetMapping(value = "/my/apps/{appId}/stores/{storeId}/app-store-qrcode")
    public String createCScanBStoreQrcode(@PathVariable String appId, @PathVariable Long storeId){

        //查询商户id
        Long merchantId = SecurityUtil.getMerchantId();
        QRCodeDto qrCodeDto = new QRCodeDto();
        qrCodeDto.setStoreId(storeId);
        qrCodeDto.setMerchantId(merchantId);
        qrCodeDto.setAppId(appId);
        //商户名称
        MerchantDTO merchantDTO = merchantService.queryMerchantById(merchantId);
        String merchantName = merchantDTO.getMerchantName();
        // 标题 %s的商品
//      String.format()方法，我们可以方便地将不同类型的数据格式化为指定样式的字符串  格式化模板字符串
        qrCodeDto.setSubject(String.format(subject, merchantName));
        // 标题 %s的应用
        qrCodeDto.setBody(String.format(body,merchantName));
        String url = transactionService.createStoreQrcode(qrCodeDto);
        //调用工具类生成二维码
        try {
          return   QRCodeUtil.createQRCode(url,200,200);
        } catch (IOException e) {
            throw new BusinessException(CommonErrorCode.E_200007);
        }
    }
}
